//
//  ViewController.m
//  20601Net
//
//  Created by student on 16/3/24.
//  Copyright © 2016年 niit. All rights reserved.localhost
//

#import "ViewController.h"

@interface ViewController ()<NSURLConnectionDataDelegate>
{
    NSMutableData *mData;
    
    int dataLength;
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    NSURL *url=[NSURL URLWithString:@"http://localhost:8080/MJServer/login?username=123&pwd=123&method=get&type=JSON"];
    NSLog(@"协议：%@",url.scheme);
    NSLog(@"主机：%@",url.host);
    NSLog(@"路径：%@",url.relativePath);
    NSLog(@"路径：%@",url.path);
    NSLog(@"端口：%@",url.port);
    NSLog(@"请求：%@",url.query);
/*
 协议：http
 主机：localhost
 路径：/MJServer/login
路径：/MJServer/login
 端口：8080
请求：username=123&pwd=123&method=get&type=JSON
 */
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//同步请求
- (IBAction)btn1Pressed:(id)sender
{
    NSURL *url=[NSURL URLWithString:@"http://localhost:8080/MJServer/login?username=123&pwd=123&method=get&type=JSON"];
    NSURLRequest *request=[NSURLRequest requestWithURL:url];
    
    NSURLResponse *response;
    
    NSError *error;
    
    NSDate *date1=[NSDate date];
    
    //发请求，同步请求
    NSData  *data=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    
    NSDate *date2= [NSDate date];
    NSTimeInterval t=[date2 timeIntervalSinceDate:date1];
    
    NSLog(@"花费了%0.3f秒",t);
    
    NSHTTPURLResponse *httpResponse=response;
    NSLog(@"状态码 %li",(long)httpResponse.statusCode);
    NSLog(@"响应头 %@",httpResponse.allHeaderFields);
    
    NSString *str=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"%@",str);
    
}

//异步 block方式
- (IBAction)btn2Pressed:(id)sender {
    //网址
    NSURL *url=[NSURL URLWithString:@"http://120.25.226.186:32812//MJServer/login?username=123&pwd=123&method=get&type=JSON"];
    //请求对象
    NSURLRequest *request=[NSURLRequest requestWithURL:url];
    
    //发请求（异步请求，不会卡住线程，在后台请求数据，数据回来后，执行block里的处理方法）
    NSDate *d1=[NSDate date];
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        
        //数据->文字
        NSString *str=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@",str);
        
    }];
    
    NSDate *d2=[NSDate date];
    NSTimeInterval t=[d2 timeIntervalSinceDate:d1];
    NSLog(@"花费了%.3f秒",t);
    
    
    //
}

//异步 代理方式


- (IBAction)btn3Pressed:(id)sender {
    NSURL *url=[NSURL URLWithString:@"http://120.25.226.186:32812/resources/images/minion_02.png"];
    
    
    // 2. 请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //3.发请求
    NSURLConnection *connection=[[NSURLConnection alloc]initWithRequest:request delegate:self];
    
    //发出请求，不会卡住界面
    mData=[NSMutableData data];
    [connection start];

}

#pragma mark - NSURLConnectionData Delegate Method
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    NSHTTPURLResponse *h=response;
    
    NSLog(@"1.接收到服务器响应 %li %@",(long)h.statusCode,h.allHeaderFields);
    NSLog(@"数据总共大小是：%@",h.allHeaderFields[@"Content-length"]);
    dataLength=[h.allHeaderFields[@"Content-Length"] intValue];
    
}

// 注意这个方法会多次运行，因为数据会被拆分成块发送，块的大小不是固定的
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    NSLog(@"2. 接收到服务器的数据%lu (进度:%i %%)",(unsigned long)data.length,(int)(mData.length * 100.0 / dataLength));
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
    NSLog(@"3. 接收完成，显示到界面");
    UIImage *img = [UIImage imageWithData:mData];
    UIImageView *imgView = [[UIImageView alloc] initWithImage:img];
    [self.view addSubview:imgView];
    imgView.frame = CGRectMake(100, 200, img.size.width, img.size.height);
}


//Post方式
- (IBAction)btn4Pressed:(id)sender
{
    // 1. 网址 POST
    NSURL *url = [NSURL URLWithString:@"http://192.168.13.11:8080/MJServer/login"];
    
    //2.请求对象
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod=@"POST";//默认GET请求，指定为POST;
    
    //字符串转换成数据放在请求体中
    NSData *postData = [@"username=123&pwd=123&method=get&type=JSON" dataUsingEncoding:NSUTF8StringEncoding];//NSString -> NSData
    request.HTTPBody = postData;
    
    NSDate *d1 = [NSDate date];
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        // 数据 -> 文字
        NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        // 显示结果
        NSLog(@"%@",str);
    }];
    
    NSDate *d2 = [NSDate date];
    NSTimeInterval t = [d2 timeIntervalSinceDate:d1];
    NSLog(@"花费了%.3f秒",t);

}



@end
